package com.module.framework.config;

import com.alibaba.fastjson.serializer.SerializeConfig;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.alibaba.fastjson.serializer.ToStringSerializer;
import com.alibaba.fastjson.support.config.FastJsonConfig;
import com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import java.util.List;

/**
 * @Author JiHuiQin
 * @Date 2022/2/14 19:14
 * @Version 1.0
 */

@Configuration
public class WebConfig implements WebMvcConfigurer {
	private static final Log log = LogFactory.getLog(WebConfig.class);

	@Value("${absoluteImgPath}")
	String absoluteImgPath;

	@Value("${sonImgPath}")
	String sonImgPath;

	@Override
	public void addResourceHandlers(ResourceHandlerRegistry registry) {
		// registry.addResourceHandler("/static/**").addResourceLocations("classpath:/web/images/");
		registry.addResourceHandler(sonImgPath + "**").addResourceLocations("file:" + absoluteImgPath);
	}

	/**
	 * 跨域
	 *
	 * @param registry
	 */
	@Override
	public void addCorsMappings(CorsRegistry registry) {
		registry.addMapping("/**")
				.allowCredentials(true)
				.allowedHeaders("*")
				.allowedOrigins("*")
				.allowedMethods("GET", "POST", "DELETE", "PUT")
				.maxAge(3600);
	}


	@Bean
	public HttpMessageConverter fastJsonHttpMessageConverters() {
		//1.需要定义一个Convert转换消息的对象
		FastJsonHttpMessageConverter fastConverter = new FastJsonHttpMessageConverter();
		FastJsonConfig fastJsonConfig = new FastJsonConfig();
		fastJsonConfig.setSerializerFeatures(SerializerFeature.PrettyFormat);
		fastJsonConfig.setDateFormat("yyyy-MM-dd HH:mm:ss");

		SerializeConfig.globalInstance.put(Long.class, ToStringSerializer.instance);

		fastJsonConfig.setSerializeConfig(SerializeConfig.globalInstance);
		fastConverter.setFastJsonConfig(fastJsonConfig);
		HttpMessageConverter<?> converter = fastConverter;
		return converter;
	}

	@Override
	public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
		converters.add(fastJsonHttpMessageConverters());
	}
}
